package com.example.demo.controller;

import com.example.demo.model.Response;
import com.example.demo.model.entity.User;
import com.example.demo.model.request.LoginRequest;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@Slf4j
@Api(tags = "用户接口")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "登录接口", notes = "登录，如果未注册直接注册")
    public Response<User> login(@RequestBody LoginRequest request, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        User user = userService.userJudge(servletRequest);
        if(user != null){
            return Response.fail(-4);
        }
        user = userService.findUserByUserName(request);
        if(user == null){
            User newUser = new User(request.getUserName(), request.getPassWord(), User.USER);
            userService.register(request);
        }
        String passWord = request.getPassWord();
        if(!passWord.equals(user.getPassWord())){
            return Response.fail(-3);
        }
        userService.updateAuthorization(servletResponse, user);
        return Response.success(user);
    }

    @GetMapping("/")
    @ApiOperation(value = "测试接口")
    public String hello(){
        return "hello";
    }

    @PostMapping("/logout")
    @ApiOperation(value = "退出登录", notes = "仅仅清除token，token还可以重复使用，需要前端清除token")
    public Response<User> logout(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        User user = userService.userJudge(servletRequest);
        if(user == null){
            return Response.fail(-1);
        }
        userService.deleteUserToken(servletResponse);
        return Response.success(user);
    }
}
